package application;

import java.awt.FileDialog;
import java.awt.Frame;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.Serializable;
import java.util.Observable;
import java.util.Observer;

import model.Commande;



/*
 * Cette classe s'occupe de l'affichage pour sauvegarder un fichier
 * texte contenant la commande du client
 */

public class PersistanceManager implements Observer
{
	
	
	   /**
	 * Method allowing, through the use of a FileDialog instance to retrieve
	 * file path to perform serialization or deserialization operations.
	 * 
	 * @return String File path to be used for serialization and deserialization
	 *         process. Returns null if user cancels action or if any other
	 *         problem is encountered.
	 */
	public String getFileSelection()
	{
		final String dialogHeader = SAVE_HEADER;

		String path = null;

		// step 1: creating a file dialog to obtain
		// user selection in terms of file.
		FileDialog dialog = new FileDialog(new Frame(), dialogHeader,1);

		// step 2: show filedialog
		dialog.setVisible(true);

		// step 3: create chosen path
		String chosenDirectory = dialog.getDirectory();
		String chosenFile = dialog.getFile();

		if (!(chosenDirectory == null || chosenFile == null))
			path = chosenDirectory + chosenFile;

		return path;

	}
	
	/*
	 * // testing purposes only public static void main(String[] args) { //
	 * serialization PersistanceManager p = new PersistanceManager();
	 * Serializable i = new Image("C:\\LAB_UML.png");
	 * System.out.println("Serializing..."); Boolean b = p.serialize(i);
	 * System.out.println("Serialization was successful: " + b.toString()); //
	 * deserialization System.out.println("Deserializing..."); Serializable s =
	 * p.deSerialize(""); if(s != null && s instanceof Serializable)
	 * System.out.println("Deserialization was successful"); else
	 * System.out.println("Deserialization was not successful."); } // end of
	 * test main
	 */

	public void update(Observable obs, Object o) {
		if(o instanceof Commande){
			Commande comm = (Commande)o;
			serialize(comm.toString());
		}
		
	}
	
	/**
	 * Serialize method allows the serialization of model component of current
	 * MVC architecture.
	 * 
	 * @param object
	 *            Object to be serialized
	 * 
	 * @return Boolean Return object indicating the status of the serialization
	 *         operation. Returns a Boolean wrapper with a value of true if the
	 *         operation completed successfully. Otherwise it returns a Boolean
	 *         wrapper with a false value.
	 */
	public Boolean serialize(final Serializable object)
	{

		Boolean result = Boolean.valueOf(false);
		String filePath;
		FileOutputStream fos;
		ObjectOutputStream oos;

		if (object == null)
			return result;

		filePath = getFileSelection();

		if (filePath == null)
			return result;

		try
		{
			fos = new FileOutputStream(filePath+".asn");
			oos = new ObjectOutputStream(fos);
			try
			{
				oos.writeObject(object);
			}
			finally
			{
				oos.flush();
				oos.close();
			}
			result = Boolean.valueOf(true);
		}
		catch (IOException ioe)
		{

			ioe.printStackTrace(); // to be replaced later
		}

		return result;
	}

	/**
	 * 
	 * Deserialize method allows the deserialization of model component of
	 * current MVC architecture.
	 * 
	 * @param path
	 *            String representation of file location containing object to be
	 *            deserialized.
	 * 
	 * @return Serializable Return serializable object once deserialization has
	 *         completed. Returns null if deserialization failed.
	 */
	/*public Serializable deSerialize()
	{
		Serializable result = null;
		String filePath;
		FileInputStream fis;
		ObjectInputStream ois;

		filePath = getFileSelection(FileDialog.LOAD);

		if (filePath == null)
        {
    			return result;
        }
		
    	String type = null;
        int i = filePath.lastIndexOf('.');
        
        if (i > 0)
        {
            type = filePath.substring(i + 1).toLowerCase();
        }
        else
        {
        	return result;
        }
        
        if (!type.equals("asn"))
        {
    			return result;
        }

		try
		{
			fis = new FileInputStream(filePath);
			ois = new ObjectInputStream(fis);
			try
			{
				Object o = ois.readObject();
				if (isDeserializationValid(o))
					result = (Serializable) o;
			}
			finally
			{
				ois.close();
			}
		}
		catch (ClassNotFoundException e)
		{
			e.printStackTrace();// to be replaced later
		}
		catch (IOException ioe)
		{

			ioe.printStackTrace(); // to be replaced later
		}

		return result;
	}*/

	

	private static final String SAVE_HEADER = "Save as...";
	private static final String LOAD_HEADER = "Load";


}
